import torch 
import torch.nn as nn
from torch.nn import functional as F 
from torchsummary import summary

class ResidualBlock(nn.Module):
    expansion = 1
    def __init__(self, input_channel, output_channel, stride=1):
        super(ResidualBlock, self).__init__()
        self.conv1 = nn.Conv2d(input_channel, output_channel, 3, stride, 1, bias=False)
        self.bn1 = nn.BatchNorm2d(output_channel)
        self.conv2 = nn.Conv2d(output_channel, output_channel, 3, 1, 1, bias=False)
        self.bn2 = nn.BatchNorm2d(output_channel)
        self.shortcut = nn.Sequential()

        if stride != 1 or input_channel != self.expansion * output_channel:
            self.shortcut = nn.Sequential(
                nn.Conv2d(input_channel, self.expansion*output_channel, 
                kernel_size = 1, stride=stride, bias=False),
                nn.BatchNorm2d(self.expansion*output_channel)
            )

    def forward(self, x):
        out = F.relu(self.bn1(self.conv1(x)))
        out = self.bn2(self.conv2(out))
        out += self.shortcut(x)
        out = F.relu(out)
        return out


class Resnet(nn.Module):
    def __init__(self, block, num_blocks, num_classes=2):
        super(Resnet, self).__init__()
        self.input_channel = 32
        self.conv1 = nn.Conv2d(3, 32, kernel_size=3, stride=2, padding=1, bias=False)
        self.bn1 = nn.BatchNorm2d(32)

        self.layer1 = self._make_layer(block, 32, num_blocks[0], stride=1)
        self.layer2 = self._make_layer(block, 32, num_blocks[1], stride=2)
        self.layer3 = self._make_layer(block, 64, num_blocks[2], stride=2)
        self.layer4 = self._make_layer(block, 64, num_blocks[3], stride=2)
        self.linear = nn.Linear(64*block.expansion, num_classes)

    def _make_layer(self, block, output_channel, block_num, stride):
        strides = [stride] + [1]*(block_num - 1)
        layers = []
        for stride in strides:
            layers.append(block(self.input_channel, output_channel, stride))
            self.input_channel = output_channel * block.expansion
        return nn.Sequential(*layers)

    def forward(self, x):
        out = F.relu(self.bn1(self.conv1(x)))
        out = self.layer1(out)
        out = self.layer2(out)
        out = self.layer3(out)
        out = self.layer4(out)
        # out = F.avg_pool2d(out, (4,16))
        out = F.adaptive_avg_pool2d(out, (1,1))
        out = out.view(out.size(0), -1)
        # print(out.shape)
        out = self.linear(out)
        # print(out.shape)
        return out

def ResNet18(num_class:int):
    return Resnet(ResidualBlock, [2, 2, 2, 2], num_classes=num_class)

# def test():
#     net = ResNet18().cuda()
#     # y = net(torch.randn(1,3,64,64))
#     # print(y.size())
#     print(summary(net,(3,64,64)))
#
# test()

